package com.data;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.util.Log;

import com.constant.Constant;
import com.net.ClientError;
import com.net.ClientException;
import com.net.RequestParameter;
/**
 * 登陆教务系统
 * 该类的功能为登陆教务系统，获取到用户名
 * 请求参数为：
 * <TextBox1>:用户名
 * <TextBox2>:密码
 * <RadioButtonList1>:用户类型
 * 
 * 返回值为:用户名和学号
 * @author mjh
 *
 */
public final class LoginEduSystemData extends BaseData
{
	private final static String TAG = "login_edu_system_data";
	/**
	 * 登陆教务系统主机名
	 */
	private final static String EDU_SUSTEM_HOST = "http://jwc.xhu.edu.cn";
	/**
	 * 登陆用户名
	 */
	private  String mUserName;
	/**
	 * 学号
	 */
	private String mNumber;
	/**
	 * 课表url
	 */
	private String mScheduleUrl;
	/**
	 * 考试查询url
	 */
	private String mExamineUrl;
	/**
	 * 成绩查询url
	 */
	private String mGradeUrl;
	/**
	 * 教师教学班名单查询
	 */
	private String mClassUrl;
	/**
	 * 登陆之后的location，只有中间的那一部分
	 */
	private String mLocation;
	/**
	 * 转发地址，为加主机名
	 */
	private String mReferer;
	/**
	 * 教学质量评价url，注意如果该url不为null，表示需要进行教学质量评价
	 */
	private String mTeachQualitUrl;
	/**
	 * 标志是否需要进行教学质量评价
	 */
	private boolean bTeachQuailit;
	
	@Override
	public void startParse(RequestParameter parameter) throws Exception, ClientException
	{
		Log.i(TAG, "开始登陆教务系统");
		// -----------第一步获取到登陆教务系统页面的转发连接地址 --------------
		String location = getLocation(EDU_SUSTEM_HOST);
		
		// -----------第二步登陆教务系统-------------------------------------
		String url = EDU_SUSTEM_HOST + location;
		
		// ---------------解析请求参数--------------------------------------
		String param = encodeParameters(parameter, "gb2312");//语言为中文
		String postData = "__VIEWSTATE=dDwtMTIwMTU3OTE3Nzs7Pqy7Rg6TVgMwX1KOyLWd5b%2Fmg1J2" + param +
				"&Button1=&lbLanguage=";
		
		
		location = getLoginEduLocation(url, postData, url);
		
		// 判断当前登陆用户是学生还是教师
		String type = parameter.getValue("RadioButtonList1");
		if(type.equals("教师"))
		{
			mReferer = location;
			mLocation = location.split("js_")[0];
			
			String stream = openConnection(EDU_SUSTEM_HOST + location);
			jsReadStream(stream);
		}
		else
		{
			mReferer = location;
			mLocation = location.split("xs_")[0];
			String stream = openConnection(EDU_SUSTEM_HOST + location);
			
			readStream(stream);
		}
		
		
		
	} // startParse
	

	
	
	private String openConnection(final String urlS) throws Exception
	{
		URL url = new URL(urlS);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();//是属于递归调用吗？？？
		connection.setDoOutput(true);
		connection.setRequestMethod("GET");
		connection.setRequestProperty("Accept", "text/html, application/xhtml+xml, */*");
		connection.setConnectTimeout(Constant.SET_CONNECTION_TIMEOUT);
		connection.setReadTimeout(Constant.SET_READ_TIMEOUT);
		connection.setUseCaches(false);
		connection.setInstanceFollowRedirects(false);
		connection.setConnectTimeout(Constant.SET_CONNECTION_TIMEOUT);
		connection.setReadTimeout(Constant.SET_READ_TIMEOUT);
		connection.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent"));
		
		connection.connect();
		if(connection.getResponseCode() != 200)
		{
			Log.i(TAG, "数据获取失败!");
			throw new ClientException("登陆教务系统失败", ClientError.ERROR_CONNECTION);
		}
		
		return getWebSource(connection.getInputStream(), "gb2312");
		
	} // openConnection
	
	
	/**
	 * 获取登陆教务系统location
	 * 
	 * @param urlS：登陆时请求url
	 * @param postData：请求数据
	 */
	private String getLoginEduLocation(final String urlS, final String postData, final String referer) throws Exception, ClientException
	{
		URL url = new URL(urlS);
		
		HttpURLConnection connection = (HttpURLConnection)url.openConnection();
		connection.setRequestMethod("POST");
		connection.setInstanceFollowRedirects(false);
		connection.setConnectTimeout(Constant.SET_CONNECTION_TIMEOUT);
		connection.setReadTimeout(Constant.SET_READ_TIMEOUT);
		connection.setDoOutput(true);
		connection.setRequestProperty("Accept", "text/html, application/xhtml+xml, */*");
		connection.setRequestProperty("Referer", referer);
		connection.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent"));
		
		OutputStream out = connection.getOutputStream();
		out.write(postData.getBytes());
		out.close();
		connection.connect();
		
		String location = null;
		
		
		// 获取Location
		if(connection.getResponseCode() == 302)
		{
			Log.i(TAG, "登陆教务系统获取转发成功");
			location = connection.getHeaderField("Location");
		}
		else if(connection.getResponseCode() == 200)
		{
			Log.i(TAG, "登陆教务系统登陆之后获取请求转发失败, 失败原因：" + connection.getResponseCode());
			throw new ClientException("教务系统登陆失败", ClientError.ERROR_PASSWD);
		}
		else
		{
			Log.i(TAG, "登录教务系统失败， 失败原因：" + connection.getResponseCode());
			throw new ClientException("登录教务系统失败", ClientError.ERROR_CONNECTION);
		}
		
		// 登陆教务系统获取到用户名
		return location;
	} // getLoginEduLocation
	
	/**
	 * 获取登陆时跳转的location
	 * @param url
	 * @return
	 */
	private String getLocation(final String urlS) throws Exception, ClientException
	{
		URL url = new URL(urlS);
		
		HttpURLConnection connection = (HttpURLConnection)url.openConnection();
		connection.setRequestMethod("GET");
		connection.setInstanceFollowRedirects(false);
		connection.setDoOutput(true);
		connection.setConnectTimeout(Constant.SET_CONNECTION_TIMEOUT);
		connection.setRequestProperty("Accept", "text/html, application/xhtml+xml, */*");
		connection.setRequestProperty("Referer", "http://xhu.edu.cn");
		connection.setConnectTimeout(Constant.SET_CONNECTION_TIMEOUT);
		connection.setReadTimeout(Constant.SET_READ_TIMEOUT);
		connection.setRequestProperty("Connection", "Keep-Alive");
		connection.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent"));
		connection.connect();
		
		String location = null;
		if(connection.getResponseCode() == 302)
		{
			Log.i(TAG, "获取转发成功");
			location = connection.getHeaderField("Location");
		}
		else
		{
			Log.i(TAG, "获取请求转发链接失败");
			throw new ClientException("登录教务系统失败", ClientError.ERROR_CONNECTION);
		}
		
		
		return location;
		
	} // getLocation
	
	/**
	 * 解析登陆用户名,
	 * 数据格式如下:
	 * <div class="info">
	 * 	<ul>
	 * 		<li>
	 * 			<span id="Label3">欢迎您：</span>
	 * 			<em><span id="xhxm">312009070102221  莫建华同学</span></em>
	 * 		</li>
	 * 		<li>
	 * 			<a id="likTc" href="javascript:__doPostBack('likTc','')">安全退出</a>
	 * 		</li>
	 * 	</ul>
	 * </div>
	 * 
	 * <ul> 
	 *  <li> <span id="Label3">欢迎您：</span> <em> <span id="xhxm">312009070102221 莫建华同学</span></em> </li>
	 *  <li> <a id="likTc" href="javascript:__doPostBack('likTc','')">安全退出</a> </li>
	 * </ul>

	 * @param stream :http请求html数据
	 * @throws Exception
	 */
	public void readStream(final String stream) throws Exception
	{
		Document document = Jsoup.parse(stream);
		Elements div = document.getElementsByClass("info");
		if(div == null)
			return;
		
		Element li = div.get(0).child(0);
		li = li.child(0);
		//<li> <span id="Label3">欢迎您：</span> <em> <span id="xhxm">312009070102221 莫建华同学</span></em> </li>
		String array[] = li.child(1).child(0).ownText().split(" ");
		mNumber = array[0];
		mUserName = array[1];
		
		Log.i(TAG, "获取登陆用户名成功");
		
		
		// 解析跟人课表请求连接和成绩查询连接
		div = document.getElementsByClass("nav");
//		//div = div.select("ul");
		Element nav = div.get(0);
//		div = nav.getElementsByClass("sub");
//		
//		Element div5 = div.get(3);
		
		Element child = nav.child(0);
		while(child != null) {
		
			
			// 获取到文本标题节点
			String title = child.child(0).child(0).ownText();
			if("教学质量评价".equals(title.trim())) {
				// 解析教学质量评价标签
				Elements teach = child.getElementsByClass("sub");
				if(teach != null) {
					bTeachQuailit = true;
				}
			}
			
			if("信息查询".equals(title.trim())) {
				// 查找到信息查询标签
				Elements infos = child.getElementsByClass("sub");
				infos = infos.select("li");
				for(int i = 0; i < infos.size(); i++) {
					Element a = infos.get(i);
					a = a.child(0);
					String text = a.ownText();//获得学生个人课表的标签
					if("学生个人课表".equals(text.trim())) {
						mScheduleUrl = EDU_SUSTEM_HOST + mLocation +  a.attr("href");
					}
					if("学生考试查询".equals(text.trim())) {
						mExamineUrl =  EDU_SUSTEM_HOST + mLocation + a.attr("href");
					}
					if("成绩查询".equals(text.trim())) {
						mGradeUrl =  EDU_SUSTEM_HOST + mLocation + a.attr("href");
					}
				} // for
			} // if
			
			child = child.nextElementSibling();
		}
		
		
		Log.i(TAG, "教务系统登陆数据解析成功");
		
	} // readStream
	
	
	/**
	 * 	 <ul class="sub">
		 <!--[if lte IE 6]><iframe class='navbug'></iframe><![endif]-->
		 <li><a href="tjkbcx.aspx?zgh=0119980049&amp;xm=刘克剑&amp;gnmkdm=N122302" target="zhuti" onclick="GetMc('专业推荐课表查询');">专业推荐课表查询</a></li>
		 <li><a href="jstjkbcx.aspx?zgh=0119980049&amp;xm=刘克剑&amp;gnmkdm=N122303" target="zhuti" onclick="GetMc('教师个人课表查询');">教师个人课表查询</a></li>
		 <li><a href="js_xkqk.aspx?zgh=0119980049&amp;xm=刘克剑&amp;gnmkdm=N122304" target="zhuti" onclick="GetMc('教学班名单查询');">教学班名单查询</a></li>
		 <li><a href="js_ksap.aspx?zgh=0119980049&amp;xm=刘克剑&amp;gnmkdm=N122306" target="zhuti" onclick="GetMc('考试安排');">考试安排</a></li>
		 <li><a href="pyjh.aspx?zgh=0119980049&amp;xm=刘克剑&amp;gnmkdm=N122307" target="zhuti" onclick="GetMc('培养计划');">培养计划</a></li>
		 <li><a href="js_cxxs.aspx?zgh=0119980049&amp;xm=刘克剑&amp;gnmkdm=N122310" target="zhuti" onclick="GetMc('学生成绩、选课情况查询');">学生成绩、选课情况查询</a></li>
		 <li><a href="js_zlpj.aspx?zgh=0119980049&amp;xm=刘克剑&amp;gnmkdm=N122314" target="zhuti" onclick="GetMc('学生评教结果查询');">学生评教结果查询</a></li>
		</ul>
	 */ 
	private void jsReadStream(final String stream)
	{
		Document document = Jsoup.parse(stream);
		
		Elements div = document.getElementsByClass("info");
		if(div == null)
			return;
		
		Element li = div.get(0).child(0);
		li = li.child(0);
		//<li> <span id="Label3">欢迎您：</span> <em> <span id="xhxm">312009070102221 莫建华同学</span></em> </li>
		String array[] = li.child(1).child(0).ownText().split(" ");
		mNumber = array[0];
		mUserName = array[1];
		
		Log.i(TAG, "获取登陆用户名成功");
		
		
		
		Elements uls = document.getElementsByClass("nav");
		if(uls == null)
			return;
		Element nav = uls.get(0);
		
		Element child = nav.child(0);
		while (child != null) {
			String title = child.child(0).child(0).ownText();
			if("信息查询".equals(title.trim())) {
				// 查找到信息查询标签
				Elements infos = child.getElementsByClass("sub");
				infos = infos.select("li");
				for(int i = 0; i < infos.size(); i++) {
					Element a = infos.get(i);
					a = a.child(0);
					String text = a.ownText();
					if("教师个人课表查询".equals(text.trim())) {
						mScheduleUrl = EDU_SUSTEM_HOST + mLocation +  a.attr("href");
					}
					if("教学班名单查询".equals(text.trim())) {
						mClassUrl =  EDU_SUSTEM_HOST + mLocation + a.attr("href");
					}
				}
			}
			
			child = child.nextElementSibling();
		}
		
		
		
//		uls = uls.select("ul");
//		if(uls == null )
//			return;
//		
//		Element ul = uls.get(3);
//		if ( ul == null )
//			return;
//		
//		mScheduleUrl = EDU_SUSTEM_HOST + mLocation +  ul.child(1).child(0).attr("href");
//		mClassUrl = EDU_SUSTEM_HOST + mLocation + ul.child(2).child(0).attr("href");
		
	}
	
	
	public String getNumber()
	{
		return this.mNumber;
	}
	
	public String getUserName()
	{
		return this.mUserName;
	}
	
	/**
	 * 返回个人课表查询地址
	 * @return
	 */
	public String getScheduleUrl()
	{
		return this.mScheduleUrl;
	}
	
	/**
	 * 返回考试查询地址
	 * @return
	 */
	public String getExamineUrl()
	{
		return this.mExamineUrl;
	}
	/**
	 * 返回成绩查询地址
	 * @return
	 */
	public String getGradeUrl()
	{
		return this.mGradeUrl;
	}
	/**
	 * 返回转发地址
	 * @return
	 */
	public String getReferer()
	{
		return EDU_SUSTEM_HOST + mReferer;
	}
	
	/**
	 * 返回教师教学班名单查询
	 * @return
	 */
	public String getClassUrl()
	{
		return this.mClassUrl;
	}
	
	public void printData()
	{
		System.out.println("number:" + mNumber);
		System.out.println("username:" + mUserName);
		
		System.out.println(mScheduleUrl);
		System.out.println(mExamineUrl);
		System.out.println(mGradeUrl);
		
		System.out.println(mLocation);
	}
}
